package com.qing.design.patterns.proxy.example.proxy;

import com.qing.design.patterns.proxy.example.some_cool_media_library.ThirdPartyYouTubeClass;
import com.qing.design.patterns.proxy.example.some_cool_media_library.ThirdPartyYouTubeLib;
import com.qing.design.patterns.proxy.example.some_cool_media_library.Video;

import java.util.HashMap;

public class YouTubeCacheProxy implements ThirdPartyYouTubeLib {

	private ThirdPartyYouTubeLib youTubeLib;
	private HashMap<String,Video> cachePopular=new HashMap<>();
	private HashMap<String,Video> cacheAll=new HashMap<>();


	public YouTubeCacheProxy() {
		this.youTubeLib = new ThirdPartyYouTubeClass();
	}

	@Override
	public HashMap<String, Video> popularVideos() {
		if(cachePopular.isEmpty()){
			cachePopular= youTubeLib.popularVideos();
		}else{
			System.out.println("已从缓存中检索到列表。");
		}
		return cachePopular;
	}

	@Override
	public Video getVideo(String videoId) {
		Video video = cacheAll.get(videoId);
		if(video==null){
			video= youTubeLib.getVideo(videoId);
			cacheAll.put(videoId,video);
		}else{
			System.out.println("从缓存中检索到视频"+videoId);
		}
		return video;
	}

	public void reset(){
		cachePopular.clear();
		cacheAll.clear();
	}
}
